package com.mt.restaurant.service.staff.impl;

import com.mt.restaurant.dao.staff.RoleSalaryDao;

import com.mt.common.core.exception.BusinessException;
import com.mt.common.core.web.base.PageDTO;
import com.mt.common.core.web.base.PageResultDTO;
import com.mt.common.core.web.base.BaseEntity;
import com.mt.common.core.web.BaseService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.mt.restaurant.entity.staff.RoleSalary;
import com.mt.restaurant.service.staff.RoleSalaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Transactional
public class RoleSalaryServiceBean extends BaseService implements RoleSalaryService {

    private static Logger logger = LogManager.getLogger();

	@Autowired
	private RoleSalaryDao roleSalaryDao;

	@Resource
	private RedisTemplate<String, List<RoleSalary>> redisTemplate;

	@Autowired
	StringRedisTemplate stringRedisTemplate;

	/**
	 * 根据分页参数查询角色薪资集合
	 *
	 * @param pageDTO 分页条件
	 */
	@Override
	public PageResultDTO findRoleSalarys(PageDTO pageDTO){
        pageDTO.setStartIndex((pageDTO.getCurrentPage()-1)*pageDTO.getPageSize());
		//TODO:请在此校验参数的合法性
		this.validateFindRoleSalarys(pageDTO);
		List<RoleSalary> roleSalaryDTOS = this.roleSalaryDao.findRoleSalarys(pageDTO);
		Long totalCount = this.roleSalaryDao.findRoleSalaryTotalCount(pageDTO);

		PageResultDTO pageResultDTO = new PageResultDTO();
		pageResultDTO.setTotalCount(totalCount);
		pageResultDTO.setDatas(roleSalaryDTOS);

		return pageResultDTO;
	}

	/**
	 * 查询全部角色薪资集合
	 *
	 */
	@Override
	public List<RoleSalary> findAllRoleSalarys(){
		return this.roleSalaryDao.findAllRoleSalarys();
	}

	/**
	 * 查询所有角色薪资集合(只提取ID 和 Name)
	 *
	 */
	@Override
	public List<RoleSalary> findAllRoleSalarysWithIdName(){
		//TODO:请在此校验参数的合法性
		this.validateFindAllRoleSalarysWithIdName();
		return this.roleSalaryDao.findAllRoleSalarysWithIdName();
	}

	/**
	 * 根据名称查询角色薪资集合(只提取ID 和 Name)
	 *
	 * @param roleSalaryName 名称
	 */
	@Override
	public List<RoleSalary> findRoleSalarysWithIdNameByName(String roleSalaryName){
		//TODO:请在此校验参数的合法性
		this.validateFindRoleSalarysWithIdNameByName(roleSalaryName);
		//TODO:缓存取对应参数
		Set<String> keys = stringRedisTemplate.keys("searchData:RoleSalary_where_roleSalaryName_" + roleSalaryName);
		List<RoleSalary> roleSalarys = new ArrayList<>();
		if (keys.isEmpty()) {
		roleSalarys = this.roleSalaryDao.findRoleSalarysWithIdNameByName(roleSalaryName);
		redisTemplate.opsForValue().set("searchData:RoleSalary_where_roleSalaryName_" + roleSalaryName, roleSalarys, 30, TimeUnit.DAYS);
		} else {
		roleSalarys = redisTemplate.opsForValue().get("searchData:RoleSalary_where_roleSalaryName_" + roleSalaryName);
		}
		return roleSalarys;
	}

	/**
	 * 根据ID查询指定的角色薪资(只提取ID 和 Name)
	 *
	 * @param roleSalaryId Id
	 */
	@Override
	public RoleSalary findRoleSalarysWithIdNameById(Long roleSalaryId){
		//TODO:请在此校验参数的合法性
		this.validateFindRoleSalarysWithIdNameById(roleSalaryId);
		return this.roleSalaryDao.findRoleSalarysWithIdNameById(roleSalaryId);
	}

	/**
	 * 根据ID查询指定的角色薪资
	 *
	 * @param roleSalaryId Id
	 */
	@Override
	public RoleSalary findRoleSalary(Long roleSalaryId){
		//TODO:请在此校验参数的合法性
		this.validateFindRoleSalary(roleSalaryId);
		return this.roleSalaryDao.findRoleSalary(roleSalaryId);
	}

	/**
	 * 根据ID查询指定的角色薪资(包含外键)
	 *
	 * @param roleSalaryId Id
	 */
	@Override
	public RoleSalary findRoleSalaryWithForeignName(Long roleSalaryId){
		//TODO:请在此校验参数的合法性
		this.validateFindRoleSalaryWithForeignName(roleSalaryId);
		return this.roleSalaryDao.findRoleSalaryWithForeignName(roleSalaryId);
	}

	/**
	 * 新增角色薪资
	 *
	 * @param roleSalary 实体对象
	 */
	@Override
	public RoleSalary saveRoleSalary(RoleSalary roleSalary){
		//TODO:请在此校验参数的合法性
		this.validateSaveRoleSalary(roleSalary);
		//TODO:填充公共参数
		this.setSavePulicColumns(roleSalary);
		Long rows = this.roleSalaryDao.saveRoleSalary(roleSalary);
		if(rows != 1)
		{
			String error = "新增保存角色薪资出错，数据库应该返回1,但返回了 "+rows;
			throw new BusinessException(error);
		}
		return roleSalary;
	}

	/**
	 * 更新角色薪资
	 *
	 * @param roleSalary 实体对象
	 */
	@Override
	public RoleSalary updateRoleSalary(RoleSalary roleSalary){
		//TODO:请在此校验参数的合法性
		this.validateUpdateRoleSalary(roleSalary);
		Long rows = this.roleSalaryDao.updateRoleSalary(roleSalary);
		if(rows != 1)
		{
			String error = "修改保存角色薪资出错，数据库应该返回1,但返回了 "+rows+",数据可能被删除";
			throw new BusinessException(error);
		}
		return roleSalary;
	}

	/**
	 * 根据ID删除角色薪资
	 *
	 * @param roleSalaryId ID
	 */
	@Override
	public void deleteRoleSalary(Long roleSalaryId){
		//TODO:请在此校验参数的合法性
		this.validateDeleteRoleSalary(roleSalaryId);

		Map<Class<? extends BaseEntity>,EntityUsage> entityUsageMap = this.checkForeignEntity(RoleSalary.class, roleSalaryId);
		if(entityUsageMap != null && entityUsageMap.size() >0){
			StringBuilder errors = new StringBuilder();
			errors.append("计划删除的数据正在被以下数引用\n");
			for(EntityUsage entityUsage : entityUsageMap.values()){
				errors.append("\t").append(entityUsage.getEntityLabel()).append("\n");
				for(Map.Entry<Long,String> entry : entityUsage.getUsageIdNames().entrySet() ){
					errors.append("\t\t").append(entry.getKey()).append("\t").append(entry.getValue()).append("\n");
				}
			}
			errors.append("，不能删除，请检查处理后再删除");
			throw  new BusinessException(errors.toString());
		}

		Long rows = this.roleSalaryDao.deleteRoleSalary(roleSalaryId);
		if(rows != 1){
			String error = "删除角色薪资出错，数据可能已经被删除";
			throw new BusinessException(error);
		}
	}

	//TODO:---------------验证-------------------

	private void validateFindRoleSalarys(PageDTO pageDTO) {
	//TODO:请使用下面方法添加数据过滤条件
	//		pageDTO.addFilter("creatorId",this.getLoginUserId());
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateRoleSalary()写法
	}

	private void validateFindRoleSalarysWithIdNameByName(String roleSalaryName) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateRoleSalary()写法
	}


	private void validateFindAllRoleSalarysWithIdName() {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateRoleSalary()写法
	}

	private void validateFindRoleSalarysWithIdNameById(Long roleSalaryId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateRoleSalary()写法
	}

	private void validateFindRoleSalary(Long roleSalaryId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateRoleSalary()写法
	}

	private void validateFindRoleSalaryWithForeignName(Long roleSalaryId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateRoleSalary()写法
	}

	private void validateSaveRoleSalary(RoleSalary roleSalary) {
	//不为空判断
	if (roleSalary.getEid() != null || roleSalary.getCreatorId() != null || roleSalary.getCreateDatetime() != null) {
	throw new BusinessException("非法请求");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateRoleSalary()写法
	}

	private void validateUpdateRoleSalary(RoleSalary roleSalary) {
	//不为空判断
	if (roleSalary.getEid() == null) {
	throw new BusinessException("唯一标识不能为空");
	}
	//是否存在判断
	if (this.roleSalaryDao.findRoleSalaryTotalCount(PageDTO.create(RoleSalary.FIELD_ID, roleSalary.getEid())) == 0) {
	throw new BusinessException("修改的角色薪资 " + roleSalary.getName() + " 不存在，修改失败，请重试或联系管理员");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateRoleSalary()写法
	}

	private void validateDeleteRoleSalary(Long roleSalaryId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateRoleSalary()写法
	}

	@Override
	public boolean canDownloadAttachment(String formName, Long id) {
	return true;
	}
}
